<?php

class UPCore
{    
    private $htmlPath = "";    
    private $domNodeList = null;

    public static $dom = null;

    public function __construct($_htmlPath)
    {
        $this->htmlPath = $_htmlPath;

        // get the DOM of the current document
        $rawHtml = file_get_contents($_htmlPath);

        $rawHtml =  preg_replace( '|\<\?php.*\?\>|sm', '', $rawHtml);

        UPCore::$dom = new DOMDocument();
        @UPCore::$dom->loadHTML($rawHtml);

    }


    public function s($el)
    {       
        $type = substr($el, 0,1);
                
        switch ($type)
        {
            case '#':
                $snode = UPCore::$dom->getElementById( substr($el,1) );

                $udel = new UPEl($snode);

                return $udel;
                

            case '.':
                $xpath = new DOMXPath($this->dom);
                $xpathQuery = "//*[@class='".substr($el,1)."']";
                $nodes = $xpath->query($xpathQuery);

                $udel = new UpDomElList($this->dom);
                return $udel;
                
            
            default:
                $snode = UPCore::$dom->getElementsByTagName($el);

                $udel = new UPElList();

                foreach ($snode as $node)
                {
                    $udel->add( new UPEl ($node) );
                }
                return $udel;
                
        }
        
    }

    /**
     * insert a text in a DOm element
     * @param <type> $str
     */
   

    /**
     *
     * @param <type> $str: name of the tag
     * @param <type> $id: the id of the tag
     * @return <type>
     */
    public function app ($_str, $id=null)
    {
        //
        $str = htmlentities($_str);
        
        if ( count($this->domNodeList) > 0 )
        {
           
            //
            foreach ( $this->domNodeList as $node )
            {
                $newNode = $this->dom->createElement( $str );

                // eventually set the id
                if ($id != null)
                {
                    $newNode->setAttribute("id", $id);
                }
                
                $node->appendChild($newNode);
            }
        }

        return $this;

    }


    public function attr ($_name, $_value)
    {
        // check the user input
        $name = htmlentities($_name);
        $value = htmlentities($_value);

        if ( count($this->domNodeList) > 0 )
        {
            foreach ( $this->domNodeList as $node )
            {
                $node->setAttribute ($name, $value);
            }
        }
    }

    public function show ()
    {
        echo UPCore::$dom->saveHTML();
    }

}

?>
